﻿Public Class Encoder
    Private M_AddrA As String
    Private M_AddrB As String
    Private m_Data As Byte()
    Public Sub New(ByVal AddrA As String, ByVal AddrB As String)
        M_AddrA = AddrA
        M_AddrB = AddrB
    End Sub
    Public Sub New()
        M_AddrA = ""
        M_AddrB = ""
    End Sub
    Public Function Encode(ByVal Command As Integer, ByVal Value As Integer) As Byte()
        Dim B(2) As Byte
        Dim S As String = Convert.ToString(Value, 2).PadLeft(16, "0")
        Dim B1 As Byte = Convert.ToByte(S.Substring(0, 8), 2)
        Dim B2 As Byte = Convert.ToByte(S.Substring(8, 8), 2)
        B(0) = CByte(Command)
        B(1) = CByte(B1)
        B(2) = CByte(B2)
        Return M_Encode(B)
    End Function
    Public Function Encode(ByVal Command As Integer, ByVal Value As Byte()) As Byte()
        Dim L As Integer = 1 + Value.Length - 1
        Dim B(L) As Byte
        B(0) = CByte(Command)
        Array.Copy(Value, 0, B, 1, Value.Length)
        Return M_Encode(B)
    End Function
    Public Function Encode(ByVal Data As Byte()) As Byte()
        Dim L As Integer = 3 + Data.Length - 1
        Dim B(L) As Byte
        B(0) = CByte(M_AddrA)
        B(1) = CByte(M_AddrB)
        B(2) = CByte(Data.Length)
        Array.Copy(Data, 0, B, 3, Data.Length)
        Return B
    End Function
    Private Function M_Encode(ByVal Data As Byte()) As Byte()
        Dim L As Integer = 3 + Data.Length - 1
        Dim B(L) As Byte
        B(0) = CByte(M_AddrA)
        B(1) = CByte(M_AddrB)
        B(2) = CByte(Data.Length)
        Array.Copy(Data, 0, B, 3, Data.Length)
        Return B
    End Function
    Public Property AddrA() As String
        Get
            Return M_AddrA
        End Get
        Set(ByVal value As String)
            M_AddrA = value
        End Set
    End Property
    Public Property AddrB() As String
        Get
            Return M_AddrB
        End Get
        Set(ByVal value As String)
            M_AddrB = value
        End Set
    End Property
End Class
